package test2;
import java.util.*;
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];//10个0
    }

    public void shiftDown(int parent) {
        int child = 2*parent+1;
        //进入这个循环 说明最起码你有左孩子
        while (child < this.usedSize) {
            if(child+1 < this.usedSize && this.elem[child] < this.elem[child+1]) {
                child++;
            }
            if(this.elem[child] > this.elem[parent]) {
                int tmp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

    //1 4 18 7 .....
    public void createBigHeap(int[] array) {
        //把需要的数据 存放到elem当中 一会儿建堆的时候 直接操作 elem数组就可以了
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }

        for (int i = (this.usedSize-1-1)/2; i >= 0 ; i--) {
            shiftDown(i);
        }
    }

    public  boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public void push(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize] = val;
        this.usedSize++;//
        //向上调整
        shiftUp(this.usedSize-1);
    }
    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while (parent >= 0) {
            if(this.elem[child] > this.elem[parent]) {
                int tmp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public int poll() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        int tmp = this.elem[0];
        this.elem[0] = this.elem[this.usedSize-1];
        this.elem[this.usedSize-1] = tmp;
        this.usedSize--;
        shiftDown(0);
        return tmp;
    }

    public boolean isEmpty() {
        return this.usedSize == 0;
    }

    public int peek() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        return this.elem[0];
    }

    public void heapSort() {
        int end = this.usedSize-1;
        while (end > 0) {
            int tmp = this.elem[0];
            this.elem[0] = this.elem[end];
            this.elem[end] = tmp;
            this.usedSize--;
            shiftDown(0);
            end--;
        }
    }
    public void show() {
        for (int i = 0; i < this.elem.length; i++) {
            System.out.print(this.elem[i]+" ");
        }
    }
}
